package com.liang.demo.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.liang.demo.mapper.AdminMapper;
import com.liang.demo.mapper.ResourceMapper;
import com.liang.demo.po.Admin;
import com.liang.demo.po.Resource;
import com.liang.demo.service.AdminCacheService;
import com.liang.demo.service.AdminService;
import com.liang.demo.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 陈琪亮
 * @version 1.0
 * @date 2021/3/18 16:38
 */
@Service
public class AdminServiceImpl implements AdminService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdminService.class);

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    //专门用来操作Redis缓存的业务类
    @Autowired
    private AdminCacheService adminCacheService;

    @Override
    public Admin getAdminInfo(Long adminId) {
        Admin admin = adminMapper.selectById(adminId);
        return admin;
    }

    @Override
    public List<Admin> getAdminAll() {
        return adminMapper.getAdminAll();
    }

    @Override
    public Admin getAdminByUsername(String username) {
        Admin admin = adminCacheService.getAdmin(username);
        if (admin != null) return admin;
        admin = adminMapper.getAdminByUsername(username);
        if(admin != null){
            adminCacheService.setAdmin(admin);
            return admin;
        }
        return null;
    }

    @Override
    public List<Resource> getPermissionList(Long id) {
        List<Resource> resourceList = adminCacheService.getResourceList(id);
        if(CollUtil.isNotEmpty(resourceList)){
            return  resourceList;
        }

        resourceList = resourceMapper.getPermission(id);
        if(CollUtil.isNotEmpty(resourceList)){
            //将数据库中的数据存入缓存中
            adminCacheService.setResourceList(id,resourceList);
        }
        return resourceList;
    }

    @Override
    public String login(String userName, String password) {
        String token = null;
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public String refreshToken(String token) {
        return jwtTokenUtil.refreshHeadToken(token);
    }
}
